package umich.max.geolocation.featextract.builders;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.bson.types.ObjectId;

import umich.max.geolocation.util.BlogUtils;

import com.mongodb.DBCursor;

import max.nlp.dal.blog.blogger.BloggerBlog;
import max.nlp.dal.blog.blogger.BloggerDB;
import max.nlp.dal.blog.blogger.BloggerPost;
import max.nlp.dal.weka.ExtractedFeature;
import max.nlp.wrappers.ml.weka.FeatureVectors;
import max.nlp.wrappers.ml.weka.WekaFeatureBuilder;
import max.nlp.wrappers.ml.weka.WekaFeatureExtractor;

@SuppressWarnings({ "rawtypes", "unchecked" })
public class PostFeatureBuilder extends WekaFeatureBuilder {

	private BloggerDB db = BloggerDB.getInstance();

	public FeatureVectors extract(String cName) {
		DBCursor itr = db.getBlogIterator();
		List<Map> featureVectorsForClass = new ArrayList<Map>();
		while (itr.hasNext()) {
			Map featureVectorsForBlog = new HashMap();
			BloggerBlog blog = new BloggerBlog(itr.next());
			if (BlogUtils.isBlogFromState(blog, cName)) {
				for (BloggerPost  post : blog.getPosts()){
					for (WekaFeatureExtractor f : featureExtractors) {
						ExtractedFeature alreadyExtractedFeature = db
								.findExtractedFeature(blog, f.getName());
						if (alreadyExtractedFeature == null) {
							Map vecs = f.extractFeaturesForObject(blog);
							featureVectorsForBlog.putAll(vecs);
							ExtractedFeature feat = new ExtractedFeature(vecs,
									f.getName(), blog.getId());
							db.saveExtractedFeature(feat);
						}
						else{
							Map vecs = alreadyExtractedFeature.getExtractedFeatures();
							featureVectorsForBlog.putAll(vecs);
						}
					}
					featureVectorsForClass.add(featureVectorsForBlog);
				}
				
			}
		}
		return new FeatureVectors(featureVectorsForClass, cName);
	}

}
